/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import entities.Subject;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Оксана
 */
public class SubjectDaoImpl extends AbstractDao implements SubjectDao {

    @Autowired
    public SubjectDaoImpl(JdbcTemplate jdbcTemplate) {
        super(jdbcTemplate);
    }   
    
    @Override
    public void create(Subject subject) {
        jdbcTemplate.update("insert into subjects (id, name) values (?, ?)", 
                subject.getId(), subject.getName());
    }

    @Override
    public List<Subject> findAll() {
        return jdbcTemplate.query("select id, name from subjects", new SubjectMapper());
    }

    @Override
    public Subject findById(Integer id) {
        return jdbcTemplate.queryForObject("select id, name from subjects where id = ?", 
                new Object[] {id}, new SubjectMapper());
    }

    @Override
    public Subject findByName(String name) {
        return jdbcTemplate.queryForObject("select id, name from subjects where name = ?",
                new Object[] {name}, new SubjectMapper());
    }

    private final static class SubjectMapper implements RowMapper<Subject>{

        @Override
        public Subject mapRow(ResultSet rs, int i) throws SQLException {
            Subject subject = new Subject();
            subject.setId(rs.getInt("id"));
            subject.setName(rs.getString("name"));
            return subject;
        }
    }
}
